﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using WoSoft.PACS.Data.CheckData;
using WoSoft.PACS.Data.DepartmentDoctor;
using WoSoft.PACS.Data.TemplateData;
using WoSoft.PACS.Document;
using DevComponents.DotNetBar.SuperGrid;
using System.Runtime.InteropServices;
using DevComponents.DotNetBar.Controls;
using WoSoft.PACS.Win.Properties;

namespace WoSoft.PACS.Win.Forms.SubForms
{
    /// <summary>
    /// 检查报告
    /// </summary>
    public partial class FrmCheckReport : FrmBase
    {
        private WordDocument wordDoc;
        //病人检查申请ID
        private string _checkappID;
        //病人检查类型
        private string _checkappType;
        //检查访问对象
        private CheckApp _checkapp;
        
        string str_jcyx = string.Empty;//检查印象
        string str_zdjy = string.Empty;//诊断建议
        string str_jcbz = string.Empty;//检查备注
        bool WriteAutoCamera = false;//是否自动打开采集窗口

        FrmCapture frmCapture = null;//图像采集界面
        FrmDicomView frmDicomView = null;//DicomView查看器

        private OutlineCategoryDataService outlineCategoryDs = new OutlineCategoryDataService();
        private OutlineWordsDataService outlineWordsDs = new OutlineWordsDataService();
        private TemplateDataService _templateDataService = new TemplateDataService();

        private ElementModel elementModel = new ElementModel();

        public FrmCheckReport(string checkappid,string checktype)
        {
            InitializeComponent();
            _checkappID = checkappid;
            _checkappType = checktype;
            _checkapp = new CheckApp();
        }

        //加载信息
        private void FrmCheckReport_Load(object sender, EventArgs e)
        {
            //结束word进程
            KillWorkProc();

            //加载报告模板
            LoadReport();

            //加载提纲
            LoadOutline();

            //加载图像
            LoadImages();

            //更新诊断建议
            wordDoc.AddWordText(str_jcyx, str_zdjy, str_jcbz);

            WriteAutoCamera = Settings.Default.WriteAutoCamera;//是否自动打开采集窗口
            //加载采集窗口
            if (WriteAutoCamera)
            {
                ShowCapture();
                //frmCapture.WindowState = FormWindowState.Minimized;
            }
        }

        //结束word进程
        private void KillWorkProc()
        {
            var procs = Process.GetProcessesByName("WINWORD");
            if (procs.Length > 0)
            {
                procs[0].Kill();
            }
        }

        //加载报告模板
        private void LoadReport()
        {
            this.WindowState = FormWindowState.Maximized;
            str_jcyx = string.Empty;//检查印象
            str_zdjy = string.Empty;//诊断建议
            str_jcbz = string.Empty;//检查备注

            try
            {
                dynamic obj = _checkapp.GetCheckReport(_checkappID);
                if (obj != null)//已经保存过的报告记录
                {
                    str_jcyx = obj.检查印象;
                    str_zdjy = obj.诊断建议;
                    str_jcbz = obj.检查备注;

                    //加载模板 
                    this.axFramerControl1.CreateNew("Word.Document");
                    var docObj = this.axFramerControl1.ActiveDocument as Microsoft.Office.Interop.Word.Document;
                    if (docObj != null)
                    {
                        docObj.Content.InsertXML(obj.报告内容);
                    }
                    wordDoc = new WordDocument(this.axFramerControl1);
                }
                else
                {
                    var templatePath = Path.Combine(Application.StartupPath, "ReportTemplate", "default.docx");
                    //加载报告模板
                    var dataBytes = _templateDataService.GetDefaultContent(_checkappType);
                    if (dataBytes == null) //判断该类型是否设置了模版，若没有设置去所有的通用模版
                    {
                        dataBytes = _templateDataService.GetDefaultContent("所有");
                        if (dataBytes == null)
                        {
                            MessageBoxEx.Show("请先设置报告模板", "模板未设置");
                            this.Close();
                            return;
                        }
                    }

                    FileStream fs = File.Create(templatePath, dataBytes.Length);
                    fs.Write(dataBytes, 0, dataBytes.Length);
                    fs.Close();

                    //加载模板
                    if (File.Exists(templatePath))
                    {
                        this.axFramerControl1.Open(templatePath);
                    }
                    else
                    {
                        throw new Exception("请设置模板,没有模板文件");
                    }
                    wordDoc = new WordDocument(this.axFramerControl1);
                    //加载病人信息到报告中
                    LoadPatientInfo();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //加载提纲与词句
        private void LoadOutline()
        {
            var dt = outlineCategoryDs.GetAllDataBy(_checkappType);

            this.advTree1.DisplayMembers = "名称";
            this.advTree1.ValueMember = "ID";
            this.advTree1.DataSource = dt;
            this.advTree1.ParentFieldNames = "ID,上级ID";
            this.advTree1.ExpandAll();
        }

        //加载检查图像
        public void LoadImages()
        {
            //加载图像信息(清除面板内容)
            imgPanls.Controls.Clear();

            var imgList = _checkapp.GetImage(this._checkappID);
            if (imgList != null && imgList.Count > 0)
            {
                foreach (var imgModel in imgList)
                {
                    if (imgModel.ImageBytes != null)
                    {
                        var bmp = ByteToImage(imgModel.ImageBytes);
                        //写入文件中
                        SaveToFile(imgModel.ImageBytes, imgModel.ID, imgModel.CaptureTime);

                        PictureBox pic = new PictureBox();
                        pic.ContextMenuStrip = this.contextMenuStrip;
                        pic.Dock = DockStyle.Top;
                        pic.Height = 150;
                        pic.Name = imgModel.ID;
                        pic.Padding = new System.Windows.Forms.Padding(5);
                        pic.Margin = new System.Windows.Forms.Padding(5);
                        pic.Image = bmp;
                        pic.BorderStyle = BorderStyle.FixedSingle;
                        pic.SizeMode = PictureBoxSizeMode.StretchImage;
                        pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick);


                        //显示编辑按钮
                        var imgEditButton = new Button();
                        imgEditButton.Name = "imgEditBtn";
                        imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                        imgEditButton.Width = 20;
                        imgEditButton.Height = 20;
                        imgEditButton.BackColor = Color.Transparent;
                        imgEditButton.Location = new Point(25, 5);
                        imgEditButton.Click += new EventHandler(imgEditButton_Click);
                        pic.Controls.Add(imgEditButton);

                        //显示编辑与删除按钮
                        var delButton = new Button();
                        delButton.Name = "delBtn";
                        delButton.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                        delButton.Width = 20;
                        delButton.Height = 20;
                        delButton.BackColor = Color.Transparent;
                        delButton.Location = new Point(5, 5);
                        delButton.Click += new EventHandler(delButton_Click);
                        pic.Controls.Add(delButton);

                        imgPanls.Controls.Add(pic);
                    }
                }
            }
        }

        void imgEditButton_Click(object sender, EventArgs e)
        {
            PictureBox pic = (sender as Button).Parent as PictureBox;
            var frmImageEdit = new FrmImageEdit(pic.Image, _checkappID,pic.Name);
            frmImageEdit.StartPosition = FormStartPosition.CenterScreen;
            frmImageEdit.ShowDialog(this);
        }

        //删除图像
        void delButton_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Parent.GetType().ToString() == "System.Windows.Forms.PictureBox")
            {
                var r = MessageBoxEx.Show("您确认要删除选中的图像吗?", "删除", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (r == DialogResult.OK)
                {
                    this.imgPanls.Controls.Remove((sender as Button).Parent);
                    //数据库删除
                    this._checkapp.DeleteImage((sender as Button).Parent.Name);
                }
            }
        }

        //加载病人信息到报到模板中
        private void LoadPatientInfo()
        {
            var dataRow = _checkapp.GetCheckAppByID(this._checkappID);
            if (dataRow != null)
            {
                elementModel.Name = dataRow["姓名"].ToString();
                if (dataRow["性别"] != null)
                {
                    var val = Convert.ToInt32(dataRow["性别"]);
                    switch (val)
                    {
                        case 1:
                            elementModel.Sex = "男";
                            break;
                        case 2:
                            elementModel.Sex = "女";
                            break;
                        default:
                            elementModel.Sex = " ";
                            break;
                    }
                }
                string nldw = string.Empty;
                switch (dataRow["年龄单位"].ToString())
                {
                    case "0":
                        nldw = "岁";
                        break;
                    case "1":
                        nldw = "月";
                        break;
                    case "2":
                        nldw = "天";
                        break;
                    case "3":
                        nldw = "小时";
                        break;
                    default:
                        nldw = "";
                        break;
                }
                elementModel.Age = dataRow["年龄"].ToString() == "0" ? "" + nldw : dataRow["年龄"].ToString() + nldw;
                elementModel.AppDepartment = dataRow["申请科室"].ToString();
                elementModel.AppDoctor = dataRow["申请医生"].ToString();
                elementModel.AppOrderNum = dataRow["申请单号"].ToString();
                elementModel.BedNum = dataRow["床号"].ToString();
                elementModel.Diagnosis = dataRow["临床诊断"] != null ? dataRow["临床诊断"].ToString() : "";
                elementModel.CheckItem = dataRow["检查项目名称"] != null ? dataRow["检查项目名称"].ToString() : "";
                elementModel.CheckTime = dataRow["申请时间"] != null ? Convert.ToDateTime(dataRow["申请时间"]).ToString("yyyy-MM-dd") : string.Empty;
                var departid = dataRow["执行科室ID"] != null ? dataRow["执行科室ID"].ToString() : string.Empty;
                if (!string.IsNullOrEmpty(departid))
                {
                    DepartmentDoctorData department = new DepartmentDoctorData();
                    var departName = department.GetDepartNameById(departid);
                    elementModel.CheckDepartment = departName;
                }
                elementModel.CheckDoctor = dataRow["检查技师"] != null ? dataRow["检查技师"].ToString() : string.Empty;
                elementModel.CheckID = dataRow["检查号"].ToString();
                elementModel.AuditDoctor = dataRow["审核医师"] != null ? dataRow["审核医师"].ToString() : string.Empty;
                //传入检查报告中
                wordDoc.UpdatePatientInfos(elementModel,Program.yymc);
            }
        }

        //保存图像到文件中
        private void SaveToFile(byte[] data, string id, DateTime createTime)
        {
            try
            {
                var timeFolder = createTime.ToString("yyyyMMdd");
                var imgPath = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder, id + ".jpg");
                var imgFolder = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder);
                if (!File.Exists(imgPath))
                {//文件不存在,则创建
                    if (!Directory.Exists(imgFolder))
                    {//检查文件目录是否存在,不存在,则创建
                        Directory.CreateDirectory(imgFolder);
                    }
                    using (MemoryStream ms1 = new MemoryStream(data))
                    {
                        Image.FromStream(ms1).Save(imgPath);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //保存记录到数据库中
        private void SaveToDB()
        {
            //保存前清空诊断建议
            foreach (Microsoft.Office.Interop.Word.ContentControl item in wordDoc.Doc.ContentControls)
            {
                switch (item.Tag)
                {
                    case "检查印象":
                        str_jcyx = item.Range.Text;
                        item.Range.Text = "";
                        break;
                    case "诊断建议":
                        str_zdjy = item.Range.Text;
                        item.Range.Text = "";
                        break;
                    case "检查备注":
                        str_jcbz = item.Range.Text;
                        item.Range.Text = "";
                        break;
                    default:
                        break;
                }
            }
            var xml = wordDoc.GetDocXML();
            _checkapp.SaveReport(_checkappID, xml, FrmMain.CurrentUser.Name, str_jcyx, str_zdjy, str_jcbz);

            //更新诊断建议
            wordDoc.AddWordText(str_jcyx, str_zdjy, str_jcbz);
        }

        //双击图像添加到报告中
        void pic_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Object myObj = this.axFramerControl1.ActiveDocument;
            if (myObj == null)
            {
                return;
            }
            //var imgPath = this.lsvImageList.SelectedItems[0].Tag.ToString();
            var imgPath = "";
            var picbox = sender as PictureBox;
            if (picbox != null)
            {
                var imgName = picbox.Name;
                var path = Path.Combine(Application.StartupPath, "CaptureImages");
                var files = Directory.GetFiles(path, imgName + ".jpg", SearchOption.AllDirectories);
                if (files.Length > 0)
                {
                    imgPath = files[0];
                    Microsoft.Office.Interop.Word.Document wdoc = (Microsoft.Office.Interop.Word.Document)myObj;

                    //第一次插入图片时自动跳到书签位置，检查图像位置
                    if (wdoc.Bookmarks.Exists("检查图像"))
                    {
                        wdoc.Bookmarks["检查图像"].Select(); //选择书签位置
                    }

                    //插入图像并设置大小
                    try
                    {
                        Microsoft.Office.Interop.Word.InlineShape inlineShape = wdoc.Application.Selection.InlineShapes.AddPicture(imgPath);
                        inlineShape.Width = 150;
                        inlineShape.Height = 150;
                        wdoc.Application.Selection.TypeText("     ");
                    }
                    catch
                    {
                        MessageBoxEx.Show("该位置不能插入报告图片，请检查！", "提示");
                    }

                    //插入图像后删除书签
                    if (wdoc.Bookmarks.Exists("检查图像"))
                    {
                        wdoc.Bookmarks["检查图像"].Delete();
                    }

                    int count = wdoc.InlineShapes.Count;
                    if (count >= 4)
                    {
                        for (int i = 1; i <= count; i++)
                        {
                            wdoc.InlineShapes[i].Width = 100;
                            wdoc.InlineShapes[i].Height = 100;
                        }
                    }

                    //插入图像并设置大小
                    //Microsoft.Office.Interop.Word.InlineShape inlineShape = wdoc.Application.Selection.InlineShapes.AddPicture(imgPath);
                    //inlineShape.Width = 195;
                    //inlineShape.Height = 150;
                }
            }
        }

        //工具栏单击事件
        private void tlsReport_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "tlsCheckApp":
                    CheckApp(e);
                    break;
                case "tlsPatientSelect":
                    PatientSelect(e);
                    break;
                case "tlsSave":         //保存到数据库中
                    SaveToDB();
                    break;
                case "tlsPrint":
                    SaveToDB();
                    Print();
                    break;
                case "tlsPrintView":
                    wordDoc.PrintView();
                    break;
                case "tlsSaveAs":
                    wordDoc.SaveAs();
                    break;
                case "tlsImage":
                    ShowCapture();
                    break;
                case "tlsScreenCapture":
                    ScreenCapture(e);
                    break;
                case "tlsDicom":
                    ShowDicomView();
                    break;
                case "tlsClose":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        //检查申请登记
        private void CheckApp(ToolStripItemClickedEventArgs e)
        {
            SubForms.FrmCheckApp appCheckForm = new SubForms.FrmCheckApp();
            if (appCheckForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this._checkappID = appCheckForm.AppCheckID;
                this._checkappType = appCheckForm.AppCheckType;

                //结束word进程
                KillWorkProc();

                //加载报告模板
                LoadReport();

                //加载提纲
                LoadOutline();

                //加载图像
                LoadImages();

                //更新诊断建议
                wordDoc.AddWordText(str_jcyx, str_zdjy, str_jcbz);
            }
        }

        //病人选择
        private void PatientSelect(ToolStripItemClickedEventArgs e)
        {
            SubForms.FrmPatientSelect frmPatientSelect = new SubForms.FrmPatientSelect();
            if (frmPatientSelect.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this._checkappID = frmPatientSelect.AppCheckID;
                this._checkappType = frmPatientSelect.AppCheckType;

                //结束word进程
                KillWorkProc();

                //加载报告模板
                LoadReport();

                //加载提纲
                LoadOutline();

                //加载图像
                LoadImages();

                //更新诊断建议
                wordDoc.AddWordText(str_jcyx, str_zdjy, str_jcbz);
            }
        }

        //屏幕截图
        private void ScreenCapture(ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "开启屏幕截图")
            {
                System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("ScreenCutter");
                foreach (System.Diagnostics.Process myProcess in myProcesses)
                {
                    myProcess.Kill();
                }
                Process.Start(Application.StartupPath + @"\ScreenCutter.exe");
                e.ClickedItem.Text = "关闭屏幕截图";
            }
            else
            {
                System.Diagnostics.Process[] myProcesses= System.Diagnostics.Process.GetProcessesByName("ScreenCutter");
                foreach (System.Diagnostics.Process myProcess in myProcesses)
                {
                    myProcess.Kill();
                }
                e.ClickedItem.Text = "开启屏幕截图";
            }
        }

        private void Print()
        {
            wordDoc.Print();
            //打印后自动完成状态
            _checkapp.Update_State(_checkappID, 4);

            //更新打印状态
            _checkapp.Update_SfPrint(_checkappID, 1);

            //标识阳性结果                   
            DialogResult dialogResult = MessageBoxEx.Show("结果是否阳性", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
                _checkapp.Update_Sfyx(_checkappID, 1);
            else
                _checkapp.Update_Sfyx(_checkappID, 0);
            //this.Close();//打印后自动关闭
        }

        //值变化事件
        private void advTree1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (this.advTree1.SelectedValue != null)
            {
                var _selectCategoryID = this.advTree1.SelectedValue.ToString();

                var dt = outlineWordsDs.GetModesByCID(_selectCategoryID);
                this.superGridControl1.PrimaryGrid.DataSource = dt;
            }
        }

        //行双击事件
        private void superGridControl1_RowDoubleClick(object sender, DevComponents.DotNetBar.SuperGrid.GridRowDoubleClickEventArgs e)
        {
            if (this.superGridControl1.PrimaryGrid.Rows.Count > 0)
            {

                var gridRow = e.GridRow as GridRow;
                if (gridRow != null)
                {
                    var text1 = gridRow["colContent"].Value.ToString();
                    var text2 = gridRow["colRemark"].Value.ToString();
                    //var text3 = gridRow["colRemark"].Value.ToString();
                    var text3 = "";
                    wordDoc.AddWordText(text1, text2, text3);
                }
            }
        }

        private void 导入IToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_checkappID)) return;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "打开(Open)";
            ofd.FileName = "";
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);//为了获取特定的系统文件夹，可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举，其中可以定义要返回路径的哪个系统目录
            ofd.Filter = "JPG图片|*.jpg|BMP图片|*.bmp|Gif图片|*.gif";// "JPG图片|*.jpg|BMP图片|*.bmp|Gif图片|*.gif";
            ofd.ValidateNames = true;     //文件有效性验证ValidateNames，验证用户输入是否是一个有效的Windows文件名
            ofd.CheckFileExists = true;  //验证路径有效性
            ofd.CheckPathExists = true; //验证文件有效性
            try
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string ID = Guid.NewGuid().ToString();
                    PictureBox pic = new PictureBox();
                    pic.ContextMenuStrip = this.contextMenuStrip;
                    pic.Name = ID;
                    pic.Dock = DockStyle.Top;
                    pic.Height = 150;
                    pic.Padding = new System.Windows.Forms.Padding(15);
                    pic.Margin = new System.Windows.Forms.Padding(3);
                    pic.ImageLocation = ofd.FileName;
                    pic.BorderStyle = BorderStyle.FixedSingle;
                    pic.SizeMode = PictureBoxSizeMode.StretchImage;
                    pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick);

                    //保存图像(到数据库)
                    var dat = FileToByte(ofd.FileName);
                    this._checkapp.SaveImage(ID, this._checkappID, dat);

                    //显示编辑按钮
                    var imgEditButton = new Button();
                    imgEditButton.Name = "imgEditBtn";
                    imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                    imgEditButton.Width = 20;
                    imgEditButton.Height = 20;
                    imgEditButton.BackColor = Color.Transparent;
                    imgEditButton.Location = new Point(25, 5);
                    imgEditButton.Click += new EventHandler(imgEditButton_Click);
                    pic.Controls.Add(imgEditButton);

                    //显示编辑与删除按钮
                    var delButton = new Button();
                    delButton.Name = "delBtn";
                    delButton.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                    delButton.Width = 20;
                    delButton.Height = 20;
                    delButton.BackColor = Color.Transparent;
                    delButton.Location = new Point(5, 5);
                    delButton.Click += new EventHandler(delButton_Click);
                    pic.Controls.Add(delButton);

                    this.imgPanls.Controls.Add(pic);

                    //复制到文件中
                    try
                    {
                        var timeFolder = DateTime.Now.ToString("yyyyMMdd");
                        var imgPath = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder, ID + ".jpg");
                        var imgFolder = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder);
                        if (!File.Exists(imgPath))
                        {//文件不存在,则创建
                            if (!Directory.Exists(imgFolder))
                            {//检查文件目录是否存在,不存在,则创建
                                Directory.CreateDirectory(imgFolder);
                            }
                            File.Copy(ofd.FileName, imgPath, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void 导出OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (contextMenuStrip.SourceControl.GetType().ToString() == "System.Windows.Forms.PictureBox")
            {
                PictureBox pictureBox = contextMenuStrip.SourceControl as PictureBox;

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "导出图像";
                saveFileDialog.Filter = "JPG图片|*.jpg|BMP图片|*.bmp|Gif图片|*.gif";
                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                if ((saveFileDialog.ShowDialog()) == DialogResult.OK)
                {
                    //复制到文件中
                    if (saveFileDialog.FileName != null)
                    {
                        try
                        {
                            var timeFolder = DateTime.Now.ToString("yyyyMMdd");
                            var imgPath = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder, pictureBox.Name + ".jpg");
                            File.Copy(imgPath, saveFileDialog.FileName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message.ToString());
                        }
                    }
                }
            }
        }

        [DllImport("user32.dll")]
        public static extern IntPtr GetActiveWindow();//获得当前活动窗体

        [DllImport("user32.dll")]
        public static extern IntPtr SetActiveWindow(IntPtr hwnd);//设置活动窗体

        private void ShowCapture()
        {
            IntPtr activeForm = GetActiveWindow();

            if (object.Equals(frmCapture, null))
            {
                frmCapture = new FrmCapture(_checkappID);
                Size size = new Size(Settings.Default.Width, Settings.Default.Height);
                frmCapture.Top = Settings.Default.Top;
                frmCapture.Left = Settings.Default.Left;
                frmCapture.Size = size;
                frmCapture.Show(this);
            }
            else
            {
                if (frmCapture.WindowState == FormWindowState.Minimized)
                {
                    frmCapture.WindowState = FormWindowState.Normal;
                }
                else
                {
                    frmCapture.Close();
                    frmCapture.Dispose();
                    frmCapture = null;
                }
                //加载图像  刷新
                //LoadImages();
            }
            SetActiveWindow(activeForm);
        }

        const int WM_COPYDATA = 0x004A;

        [StructLayout(LayoutKind.Sequential)]
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
        // 接收窗体间消息    
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            bool WatchPortMsg = true;
            switch (m.Msg)
            {
                //接收自定义消息 USER，并显示其参数
                case WM_COPYDATA:
                    if (WatchPortMsg)
                    {
                        COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                        Type mytype = mystr.GetType();
                        mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                        try
                        {
                            PictureBox pic = new PictureBox();
                            pic.ContextMenuStrip = this.contextMenuStrip;
                            pic.Name = mystr.lpData.Split('|')[0];
                            pic.Dock = DockStyle.Top;
                            pic.Height = 150;
                            pic.Padding = new System.Windows.Forms.Padding(15);
                            pic.Margin = new System.Windows.Forms.Padding(3);
                            pic.ImageLocation = mystr.lpData.Split('|')[1];
                            pic.BorderStyle = BorderStyle.FixedSingle;
                            pic.SizeMode = PictureBoxSizeMode.StretchImage;
                            pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick);


                            //保存图像(到数据库)
                            var dat = FileToByte(mystr.lpData.Split('|')[1]);
                            if (!string.IsNullOrEmpty(this._checkappID))
                                this._checkapp.SaveImage(mystr.lpData.Split('|')[0], this._checkappID, dat);

                            //显示编辑按钮
                            var imgEditButton = new Button();
                            imgEditButton.Name = "imgEditBtn";
                            imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                            imgEditButton.Width = 20;
                            imgEditButton.Height = 20;
                            imgEditButton.BackColor = Color.Transparent;
                            imgEditButton.Location = new Point(25, 5);
                            imgEditButton.Click += new EventHandler(imgEditButton_Click);
                            pic.Controls.Add(imgEditButton);

                            //显示编辑与删除按钮
                            var delButton = new Button();
                            delButton.Name = "delBtn";
                            delButton.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                            delButton.Width = 20;
                            delButton.Height = 20;
                            delButton.BackColor = Color.Transparent;
                            delButton.Location = new Point(5, 5);
                            delButton.Click += new EventHandler(delButton_Click);
                            pic.Controls.Add(delButton);

                            this.imgPanls.Controls.Add(pic);
                        }
                        catch { }
                        //switch (mystr.lpData)
                        //{
                        //    case "refresh":
                        //        LoadImages();//刷新列表
                        //        break;
                        //    default:
                        //        break;
                        //}
                    }
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        private void ShowDicomView()
        {
            if (object.Equals(frmDicomView, null))
            {
                frmDicomView = new FrmDicomView(_checkappID);
                frmDicomView.Show(this);
            }
            else
            {
                frmDicomView.Hide();
                frmDicomView.Dispose();
                frmDicomView = null;
                //加载图像  刷新
                LoadImages();
            }
        }

        private void FrmCheckReport_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!object.Equals(frmCapture, null))//释放资源
            {
                frmCapture.Close();
                frmCapture.Dispose();
            }
        }
    }
}
